package top.jacktgq.concurrent_utils.semaphore;

import top.jacktgq.utils.LogUtils;
import top.jacktgq.utils.Sleeper;

import java.util.concurrent.Semaphore;

/**
 * @Author CandyWall
 * @Date 2020/11/5--23:54
 * @Description 测试使用信号量
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        //1、创建一个Semaphore对象
        Semaphore semaphore = new Semaphore(3);
        //2、10个线程同时运行
        for (int i = 1; i <= 10; i++) {
            new Thread(() -> {
                try {
                    //可以对同时访问共享资源的线程的个数进行限定
                    semaphore.acquire();
                    LogUtils.log("SemaphoreDemo", "running...");
                    Sleeper.sleep(1);
                    LogUtils.log("SemaphoreDemo", "end...");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            }, "t" + i).start();
        }
    }
}